package com.example.demo.controller;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RequestMapping("/home")
@RestController
public class CaptchaController {
    private static final String KAPTCHA_SESSION_KEY = "HOME_KAPTCHA_SESSION_KEY";
    private static final String KAPTCHA_SESSION_DATE = "HOME_KAPTCHA_SESSION_DATE";
    private final static long VALID_MILLIS_TIME = 60 * 1000L;//比对日期
    //验证成功：true
    //验证失败：false
    //从session获取生成的验证码 》 比对前端传递的验证码和session中存储的是否一样
    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session) {
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        //从Seesion获取验证码
        String saveCaptcha = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date saveDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);
        //比对验证码
        if(captcha.equals(saveCaptcha)){
            if(saveDate==null || System.currentTimeMillis() - saveDate.getTime()<VALID_MILLIS_TIME){
                return true;
            }
            return false;
        }
        return false;
    }
}
